package org.example.tool;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;

public class HuffmanTreeInputStream {
    private DataInputStream inputStream;
    public HuffmanTreeInputStream(InputStream inputStream) {
        this.inputStream = new DataInputStream(inputStream);
    }

    public HuffmanTree.Node readNode() throws IOException {
        char c = inputStream.readChar();
        if(c == '\\') {
            c = inputStream.readChar();
        }
        else if (c == 0) {
            return null;
        }
        else if (c == 1) {
            HuffmanTree.Node newNode = new HuffmanTree.Node();
            newNode.zero = readNode();
            newNode.one = readNode();
            return newNode;
        }
        HuffmanTree.Node newNode = new HuffmanTree.Node(c);
        return newNode;
    }
    public HuffmanTree readTree() throws IOException {
        HuffmanTree.Node root = readNode();
        return new HuffmanTree(root);
    }

    public void close() throws IOException {
        this.inputStream.close();
    }

}
